using System;
using System.Collections.Generic;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

using Xfinity.AI.Entities;
using Xfinity.Engine;
using Xfinity.ParticleSystems;
using Xfinity.Physics;
using Xfinity.Rendering;
using System.Xml.Serialization;

namespace Xfinity.ParticleSystems
{

    public class ParticleSystem : LogicalEntity, IDrawable
    {

        private VertexPositionColor[] points;
        private List<Particle> livingParticles;
        private Effect pointEffect;
        /// <summary>
        /// Gets the living particles.
        /// </summary>
        /// <value>The living particles.</value>
        public List<Particle> LivingParticles
        {
            get { return livingParticles; }
        }
        public ParticleSystem():this(1, new Xfinity.ParticleSystems.Emitters.PointEmitter(),"")
        {

        }

        private Texture2D texture;

        /// <summary>
        /// Gets or sets the texture.
        /// </summary>
        /// <value>The texture.</value>
        [XmlIgnore]
        public Texture2D Texture
        {
            get { return texture; }
            set { texture = value; }
        }


        private int maxParticles;

        /// <summary>
        /// Gets the maximum number of particles.
        /// </summary>
        /// <value>The maximum number of particles.</value>
        public int MaxParticles
        {
            get { return maxParticles; }
            set
            {
                maxParticles = value;
                livingParticles.Capacity = maxParticles;

            }
        }

        //BasicEffect basicEffect;
        //VertexDeclaration vertexDeclaration;



        public override void Initialize()
        {
            //vertexDeclaration = new VertexDeclaration(GraphicsHelper.GraphicsDevice, VertexPositionNormalTexture.VertexElements);

            //basicEffect = new BasicEffect(GraphicsHelper.GraphicsDevice, null);
            //basicEffect.EnableDefaultLighting();

            //basicEffect.View = GraphicsHelper.ActiveCamera.ViewMatrix;
            //basicEffect.Projection = GraphicsHelper.ActiveCamera.Projection;

            base.Initialize();
        }


        private ParticleEmitter emitter;

        /// <summary>
        /// Gets the emitter.
        /// </summary>
        /// <value>The emitter.</value>
        public ParticleEmitter Emitter
        {
            get { return emitter; }
        }
        private float particleEmissionRate;
        private int emissionRateMilliHertz;
        /// <summary>
        /// Gets or sets the number of particles to emit per second.
        /// </summary>
        /// <value>The particle emission rate, in Hertz.</value>
        public float ParticleEmissionRate
        {
            get { return particleEmissionRate; }
            set
            {
                System.Diagnostics.Debug.Assert(value >= 0);
                particleEmissionRate = value;
                emissionRateMilliHertz = (int)(1000 / value);
            }
        }


        public override void Update(Microsoft.Xna.Framework.GameTime gameTime)
        {
            Particle p;
            float s = (float)gameTime.ElapsedRealTime.TotalMilliseconds;
            for (int i = 0; i < livingParticles.Count; i++)
            {
                if (livingParticles[i].Age > livingParticles[i].DeathAge)
                {
                    livingParticles.Remove(livingParticles[i]);
                    continue;
                }
                p = livingParticles[i];

                p.Age += s;
                p.Acceleration =PhysicsManager.GlobalGravity;                               // * livingParticles[i].Mass;
                p.Velocity += s * p.Acceleration*s;
                p.Position += s * p.Velocity*s;

                livingParticles[i] = p;
            }

            //add more particles
            int count = maxParticles - livingParticles.Count > emissionRateMilliHertz ? maxParticles - livingParticles.Count : emissionRateMilliHertz;
            System.Diagnostics.Debug.Assert(count >= 0);
            for (int i = 0; i < count; i++)
            {
                livingParticles.Add(emitter.GenerateNewParticle());
            }

            points = new VertexPositionColor[livingParticles.Count];
            for (int i = 0; i < livingParticles.Count; i++)
            {
                p = livingParticles[i];
                points[i] = new VertexPositionColor(p.Position, p.Color);
            }


            base.Update(gameTime);
        }
        protected override void LoadGraphicsContent(bool loadAllContent)
        {
            pointEffect = GameManager.Content.Load<Effect>(@"Content\Effects\PointSPriteShader");
            texture = GameManager.Content.Load<Texture2D>(textureName);
            pointEffect.Parameters["SpriteTexture"].SetValue(texture);
        }
        string textureName;
        public ParticleSystem(int maxParticles, ParticleEmitter emitter, string textureName)
            : base()
        {
            this.maxParticles = maxParticles;
            livingParticles = new List<Particle>(maxParticles);
            this.emitter = emitter;
            this.textureName = textureName;
        }
        public override void Draw(GameTime gameTime)
        {
            pointEffect.Parameters.GetParameterBySemantic("WORLDVIEWPROJECTION").SetValue(GraphicsHelper.ActiveCamera.ViewProjectionMatrix);
            
            base.Draw(gameTime);
        }

    }
}
